// 烹饪系统 - 数据层
import { ingredientsData, recipesData } from './data.js';

// 烹饪管理器类 - 数据层处理
class CookingManager {
    constructor() {
        // 保持简洁，只管理数据逻辑
    }
    
    // 检查角色是否有所需材料
    hasRequiredIngredients(character, ingredients) {
        const inventory = character.inventory || [];
        
        return Object.entries(ingredients).every(([ingredientId, requiredAmount]) => {
            const item = inventory.find(i => i.id === ingredientId);
            return item ? item.quantity >= requiredAmount : false;
        });
    }
    

    
    // 烹饪食谱 - 返回操作结果
    cookRecipe(character, recipeId) {
        const recipe = recipesData[recipeId];
        if (!recipe) {
            return { success: false, message: '食谱不存在' };
        }
        
        // 检查技能等级
        const hasRequiredLevel = character.getSkillLevel('加工') >= recipe.requiredLevel || 
                               character.getSubSkillPoints('加工', '食品加工') >= recipe.requiredLevel;
        if (!hasRequiredLevel) {
            return { 
                success: false, 
                message: `需要${recipe.requiredSkill}等级${recipe.requiredLevel}` 
            };
        }
        
        // 检查材料
        if (!this.hasRequiredIngredients(character, recipe.ingredients)) {
            return { success: false, message: '材料不足' };
        }
        
        // 消耗材料
        Object.entries(recipe.ingredients).forEach(([ingredientId, amount]) => {
            character.removeItem(ingredientId, amount);
        });
        
        // 获得成品食物 - 创建完整的食物对象
        const foodItem = {
            id: recipeId,
            name: recipe.name,
            quantity: 1,
            description: recipe.description,
            effects: recipe.effects
        };
        // 使用新的addItem接口，传入id、quantity和name参数
        character.addItem(foodItem.id, foodItem.quantity, foodItem.name);
        
        // 增加烹饪经验 - 使用角色实例的方法
        const experiencePoints = recipe.experience || 10;
        const levelUpResult = character.increaseSkillPoints('加工', '食品加工', experiencePoints); //fix:没有升级提示弹窗
        
        return { 
            success: true, 
            message: `成功烹饪${recipe.name}！`,
            recipe: recipe
        };
    }
    
    // 使用食材或食物 - 返回操作结果
    useIngredient(character, itemId) {
        const inventory = character.inventory || [];
        
        const item = inventory.find(i => i.id === itemId);
        if (!item || item.quantity <= 0) {
            return { success: false, message: '物品不足' };
        }
        
        // 获取物品效果
        let effects = {};
        
        // 检查是否是食谱（成品食物）
        if (recipesData[itemId]) {
            effects = recipesData[itemId].effects;
        }
        // 检查是否是有效果的食材
        else if (ingredientsData[itemId] && ingredientsData[itemId].effects) {
            effects = ingredientsData[itemId].effects;
        }
        // 检查是否是基础资源（如食物）
        else if (itemId === 'food' && item && item.type === 'resource') { //fix:现在已经没有food这个类型了
            effects = { stamina: 10 };
        }
        
        if (Object.keys(effects).length === 0) {
            return { success: false, message: '该物品不能直接使用' };
        }
        
        // 应用效果
        this.applyFoodEffects(character, effects);
        
        // 消耗物品
        character.removeItem(itemId, 1);
        
        return { success: true, message: '使用成功！', effects: effects };
    }
    
    // 应用食物效果
    applyFoodEffects(character, effects) {
        // 应用精力恢复
        if (effects.stamina) {
            character.stamina = Math.min(100, character.stamina + effects.stamina);
        }
        
        // 应用健康恢复
        if (effects.health) {
            character.health = Math.min(100, character.health + effects.health);
        }
        
        // 应用快乐度恢复
        if (effects.happiness) {
            character.happiness = Math.min(100, character.happiness + effects.happiness);
        }
    }
    
    // 增加烹饪经验 - 方法保留但使用角色实例的接口
    increaseCookingExperience(character, points) {
        // 使用角色实例的方法增加技能点
        return character.increaseSkillPoints('加工', '食品加工', points);
    }
    
    // 获取角色可烹饪的食谱列表
    getAvailableRecipes(character) {
        const availableRecipes = [];
        // 使用角色实例的技能数据
        Object.entries(recipesData).forEach(([recipeId, recipe]) => {
            const hasRequiredLevel = character.getSkillLevel('加工') >= recipe.requiredLevel || 
                                   character.getSubSkillPoints('加工', '食品加工') >= recipe.requiredLevel;
            
            if (hasRequiredLevel) {
                availableRecipes.push({
                    id: recipeId,
                    ...recipe,
                    canCook: this.hasRequiredIngredients(character, recipe.ingredients)
                });
            }
        });
        
        return availableRecipes;
    }
    
    // 获取角色可用的烹饪材料
    getAvailableMaterials(character) {
        const materials = [];
        const inventory = character.inventory || [];
        
        // 处理数组格式的inventory
        inventory.forEach(item => {
            if (item && ingredientsData[item.id] && item.quantity > 0) {
                materials.push({
                    id: item.id,
                    ...ingredientsData[item.id],
                    quantity: item.quantity
                });
            }
        });
        
        return materials;
    }
}

// 创建单例实例
const cookingManager = new CookingManager();

// UI相关的辅助函数 - 这些函数可以移到UI层模块
function getEffectName(effect) {
    const effectNames = {
        stamina: '精力',
        health: '健康',
        happiness: '快乐'
    };
    return effectNames[effect] || effect;
}

// 导出管理器和辅助函数
export {
    cookingManager,
    getEffectName
};